<template>
     <div class="app-container">
  <div class="head-container">
    <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="85px" >
        <el-row :gutter="10">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
              <el-form-item label="交接日期">
                <el-date-picker
                  v-model="busDate"
                  type="date"
                  style="width: 100%;"
                  default-value
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单号" >
              <el-input v-model="code" disabled/>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="交接人">
              <zSelect v-model="handoverUserIds" :showName="handoverUserName"
                  :value.sync="handoverUserIds" :multiple="true"
                  url="api/dropDown/sysUserList"
                  style="width: 100%"/>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="结算人" >
              <zSelect v-model="settleUserIds"
                  :showName="settleUserName"
                  :value.sync="settleUserIds" :multiple="true"
                  url="api/dropDown/sysUserList"
                  style="width: 100%"/>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item  prop="isSettleAll" label="是否结清">
            <el-select  v-model="isSettleAll"  class="filter-item" clearable  placeholder="是否结清" size="small" disabled tyle="width: 100%;" >
                  <el-option
                    v-for="item in dict.common_yes_or_no"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select
                  v-model="orderStatus"
                  class="filter-item"
                  clearable
                  placeholder="状态"
                  size="small"
                  style="width: 100%" disabled
                  @change="crud.toQuery"
                >
                  <el-option
                    v-for="item in dict.common_order_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="remark" clearable placeholder="请输入备注" />
              </el-form-item>
            </el-col>
        </el-row>
    </el-form>
    </div>
    <crudOperation  :permission="permission"/>
    <el-button slot="right" class="filter-item" size="mini" type="primary" :loading="crud.rejectLoading" @click="save"> 保存 </el-button>
    <el-button slot="right" class="filter-item" size="mini" type="primary" :loading="crud.rejectLoading" @click="del"> 删除 </el-button>
    <el-button slot="right" class="filter-item" size="mini" type="primary" :loading="crud.rejectLoading" @click="delChoose"> 删除明细 </el-button>
    <el-button slot="right" class="filter-item" size="mini" type="danger" :loading="crud.rejectLoading" @click="recycles"> 回收 </el-button>
    <el-button slot="right" class="filter-item" size="mini" type="primary" :loading="crud.rejectLoading" @click="settle"> 结算 </el-button>
    <el-button slot="right" class="filter-item" size="mini" type="primary" :loading="crud.rejectLoading" @click="drawOrders"> 追加 </el-button>
    <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          :loading="crud.rejectLoading"
          @click="crud.doDetailPassOrReject('PASS', id)"
          v-permission="permission.pass">
          审核
        </el-button>
        <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
          @click="crud.doDetailPassOrReject('REJECT', id)">
          反审
        </el-button>
        <!-- <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView"
        >打印
        </el-button>
        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
        >打印预览
        </el-button> -->
    <el-table ref="table" stripe border v-loading="crud.loading" :data="data" size="small" style="width: 100%;" @row-click="crud.selectRow" height="700" @selection-change="crud.selectionChangeHandler"
    :summary-method="sumRow" show-summary>
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/>
        <el-table-column prop="busDate" label="业务日期" />
        <el-table-column prop="sourceCode" label="单据编号" />
        <el-table-column prop="sourceType" label="单据类型">
          <template slot-scope="scope">
          {{ dict.label.dict_receipt_handover_order_type[scope.row.sourceType] }}
        </template>
        </el-table-column>
      <el-table-column prop="slipCode" label="回单编码"/>
      <el-table-column prop="slipTaxAmount" label="回单金额"/>
        <el-table-column prop="sCustomerName" label="所属二批" />
        <el-table-column prop="pCustomerName" label="所属总店" />
        <el-table-column prop="customerCode" label="客户编码" />
        <el-table-column prop="customerName" label="客户名称" />
        <el-table-column prop="customerAreaName" label="客户区域" />
        <el-table-column prop="customerTypeName" label="客户分类" />
        <el-table-column prop="isRecycle" label="是否回收">
          <template slot-scope="scope">
          {{ dict.label.common_yes_or_no[scope.row.isRecycle] }}
        </template>
        </el-table-column>
        <el-table-column prop="isSettle" label="是否结算">
          <template slot-scope="scope">
          {{ dict.label.common_yes_or_no[scope.row.isSettle] }}
        </template>
        </el-table-column>
        <el-table-column prop="userName" label="人员" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column prop="receiveDate" label="应收日期" />
        <el-table-column prop="unCancelAmount" label="未核销金额" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="isSettleAll" label="是否结清">
          <template slot-scope="scope">
          {{ dict.label.common_yes_or_no[scope.row.isSettleAll] }}
        </template>
        </el-table-column>
    </el-table>
    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="slipHandover"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.detailedPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
    <el-dialog  title="打印预览"
                destroy-on-close
                v-dialogDrag
                close-on-press-escape
                :visible.sync="showPdf" append-to-body width="50vw">
      <j-pdf :src="pdfSrc" ></j-pdf>
    </el-dialog>
  </div>
</div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import { getAreaTree } from '../../../api/erp/basCustomerArea';
import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
import {getDepts} from "@/api/system/dept";
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import rrOperation from '@crud/RR.operation'
import {get,passOrReject,removeDetails,recycle,settle,drawOrders,save,del} from '@/api/erp/receiptHandover'
import crudReceiptHandover from '@/api/erp/receiptHandover'
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
import { debounce } from '../../../utils/auth';
const defaultCrud = CRUD({
    title: '回单交接明细',
    url: '/api/slipHandover/detail', sort: '', crudMethod: { ...crudReceiptHandover },
    params() {
    const href = location.href.split('/')
    console.log(href,'90909')
    return {
      id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1],
    }
  },
    optShow: {
    print: true,
    printDetail: true,
  },
  })
const defaultForm = { }
export default {
    name: 'slipHandoverDetail',
    components: { crudOperation,rrOperation,Treeselect,jPrintConfig},
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    dicts: ['dict_receipt_handover_order_type','common_yes_or_no','common_order_status'],
data(){
    return {
      permission: {
        del: ['admin', 'slipHandoverDetail:del'],
        export: ['admin', 'slipHandoverDetail:export']
      },
      data:[],
      resdata:[],
      handoverPersonList:[],
      settlePersonList:[],
      busDate:'',
      code:'',
      remark:'',
      isSettleAll:'',
      settleUserName:'',
      handoverUserName:'',
      handoverUserIds:'',
      settleUserIds:'',
      orderStatus:'',
      pdfSrc:'',
      showPdf:false,
    }
},
updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  // created() {
  //   this.onGet()
  // },
  activated(){
    this.onGet()
  },
  mounted() {
    this.crud.props.searchToggle =false
  },
methods:{
    onGet:debounce(function(){
      this.crud.loading=true
      const href = location.href.split('/')
      get({id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1]}).then(res=>{
        this.resdata=res.data
        this.data=res.data.detailList
        this.handoverPersonList=res.data.handoverPersonList
        this.settlePersonList=res.data.settlePersonList
        this.busDate=res.data.busDate
        this.code=res.data.code
        this.remark=res.data.remark
        this.isSettleAll=res.data.isSettleAll
        this.orderStatus=res.data.orderStatus
        this.settleUserIds=res.data.settleUserIds
        this.handoverUserIds=res.data.handoverUserIds
        this.settleUserName = res.data.settleUserName
        this.handoverUserName = res.data.handoverUserName
        this.crud.loading=false
      })
    }),
    sumRow({ columns, data }){
      console.log(this.crud)
      const sums = []
      for (let i in  columns) {
        if (['unCancelAmount'].includes(columns[i].property)) {
          let selectSum = 0
          let unCancelAmount=this.$refs.table._props.data.map(item=>{
            return item.unCancelAmount
          }).reduce((a,b)=>a+b)
          this.$refs.table.selection.forEach(item => {
            selectSum += item[columns[i].property]
          })
          sums[i] = <p>{selectSum.toFixed(2)*1}
            <hr/>
            {unCancelAmount || 0}</p>
        }
        sums[0] = <p>选中
          <hr/>
          合计</p>
      }
      return sums
    },
    delChoose() {
      const ids = this.$refs.table.selection.map(item => item.id)
      const datas = this.$refs.table.selection
        if(this.crud.selections.length==0){
        this.$message({
          message: '请先勾选！',
          type: 'error'
        })
        return false
      }
        removeDetails(ids).then(res => {
          this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.$alert(res.msg, '提示')
          this.onGet()
          }).catch(() => {
      })
        })

    },
    recycles(){
      const ids = this.$refs.table.selection.map(item => item.id)
      console.log(ids,'000')
     recycle(ids).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    settle(){
      const ids = this.$refs.table.selection.map(item => item.id)
      settle(ids).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
            this.$router.push({path: '/redirect/finance/financeSettlementDetail/' + res.data,query:{}})
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    drawOrders(){
      this.$router.push({path: '/redirect/finance/slipHandoverAdd/' + this.$route.params.id,query:{
        busDate:this.busDate,
        handoverUserIds:this.handoverUserIds,
        settleUserIds:this.settleUserIds,
        handoverUserName:this.handoverUserName,
        settleUserName:this.settleUserName
      }})
    },

    save(){
      this.resdata.busDate=this.busDate,
      this.resdata.remark=this.remark,
      this.resdata.handoverUserIds=this.handoverUserIds,
      this.resdata.settleUserIds=this.settleUserIds
      this.resdata.settleUserName=this.settleUserName
      this.resdata.handoverUserName=this.handoverUserName
      this.resdata.orderStatus=this.orderStatus
      console.log(this.settleUserName,'6666',this.settleUserIds)
      if (this.settleUserIds)
      this.resdata.settlePersonList = this.settleUserIds.split(',').map(res=>{
        return {
        userId: res
      }})
      if (this.handoverUserIds)
      this.resdata.handoverPersonList = this.handoverUserIds.split(',').map(res=>{
        return {
        userId: res
      }})
      save(this.resdata).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    del(){
      let ids=[this.$route.params.id]
      del(ids).then(res=>{
        if (res.status === 200){
          this.$message.success(res.msg)
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    [CRUD.HOOK.beforeRefresh]() {
      this.onGet()
      return false
    },
}
}
</script>

<style scoped>
.flex{
display: flex;
justify-content: center;
}
.mt{
  margin-top: 10px;
}
</style>
